<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- <button onclick="send()">发送请求</button> -->

    <script>
      function send(url) {
        return new Promise((resolve, reject) => {
          let req = new XMLHttpRequest();

          req.open("get", url, true);

          req.onreadystatechange = () => {
            if (req.status == 200 && req.readyState == 4) {
              // 请求成功
              resolve(req.responseText);
            }
          };

          req.onerror = () => {
            reject(req);
          };

          req.send();
        });
      }

      let promise = send("http://localhost/test");

      //  当异步请求有结果时
      promise.then((response) => {
        console.log("请求成功", response);
      });

      /**
       *    使用 promise 实现请求重连
       *    send(url='', count=3)  // 最多发送3次请求
       */
    </script>
  </body>
</html>
